package com.system.analysis;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.system.analysis.key.KeyAnalysisData;
import com.system.analysis.key.KeyAnalysisInit;
import com.system.analysis.key.KeyAnalysisInitService;
import com.system.comm.utils.FrameJsonUtil;
import com.system.comm.utils.FrameStringUtil;

/**
 * 从文本中分析出关键对象的信息
 * @author JiMMY 
 * @date 2021年5月23日 下午8:07:38
 */
public class KeyAnalysisUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(KeyAnalysisUtil.class);

	/**
	 * 初始化数据源
	 * @param init
	 * @param period	执行更新数据间隔时间[单位:s]
	 */
	public static void init(KeyAnalysisInit init, int period) {
		// 优先初始化
		init.init();
		LOGGER.info("初始化Key分析的数据源成功");
		ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
				Thread thread = new Thread(r);
				LOGGER.info("初始更新Key分析的数据源的线程:" + thread.getName());
				return thread;
			}
		});
		//线程，每隔30秒调用一次
		Runnable runnable = new Runnable() {
			public void run() {
				// 初始化原始数据
				init.init();
				LOGGER.info("更新Key分析的数据源成功");
			}
		};
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间  
		service.scheduleAtFixedRate(runnable, 10, period, TimeUnit.SECONDS);
	}

	/**
	 * 分析文本
	 * @param dataSource
	 * @param analysisText
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static List analysis(String dataSource, String analysisText) {
		List<Object> list = new ArrayList<>();
		List<String> infoList = new ArrayList<>();
		List<String> textList = FrameStringUtil.toArray(analysisText, "\n");
		for (String string : textList) {
			if (FrameStringUtil.isEmpty(string)) {
				continue;
			}
			List<String> cld1List = FrameStringUtil.toArray(string, "\t");
			for (String string1 : cld1List) {
				if (FrameStringUtil.isEmpty(string1)) {
					continue;
				}
				List<String> cld2List = FrameStringUtil.toArray(string1, " ");
				for (String string2 : cld2List) {
					if (FrameStringUtil.isEmpty(string2)) {
						continue;
					}
					infoList.add(string2.trim());
				}
			}
		}
		for (String key : infoList) {
			Object value = KeyAnalysisData.getBasicData(dataSource, key);
			if (value != null) {
				list.add(value);
			}
		}
		return list;
	}
	
	public static void main(String[] args) {
		String analysisText = "123 key1 是的 key2";
		KeyAnalysisInit init = new KeyAnalysisInitService();
		KeyAnalysisUtil.init(init, 30);
		String dataSource = "0";
		@SuppressWarnings("unchecked")
		List<String> list = KeyAnalysisUtil.analysis(dataSource, analysisText);
		
		System.out.println(FrameJsonUtil.toString(list));
	}
}
